package mdm.led.controller;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import mdm.led.common.AjaxResponse;
import mdm.led.common.Constant;
import mdm.led.common.LocalConfig;
import mdm.led.entity.three.FindThreeTaskSelf;
import mdm.led.entity.three.ThreeItem;
import mdm.led.entity.three.ThreeMainList;
import mdm.led.entity.three.ThreeTaskAllot;
import mdm.led.entity.three.ThreeTaskSelf;
import mdm.led.entity.three.UpdateThreeTaskAllot;
import mdm.led.service.ThreeTableService;
import mdm.led.util.ListToString;

/**
 *
 * @author :Monarch丿He
 * @date :2018年12月17日
 * @explain :
 */
@Controller
@RequestMapping(value = "threeTableApp")
@Api(description = "督导三查App")
public class ThreeTableAppController {

	private Logger logger = Logger.getLogger(ThreeTableAppController.class);
	@Autowired
	protected LocalConfig localConfig;
	@Autowired
	private ThreeTableService threeTableService;

	@ApiOperation(value = "1:(检查人/抽查人)--科室/大队  主列表 ", notes = "userID : 当前用户ID<br>tableType :模块标识  >> 2:科室 3:大队")
	@ResponseBody
	@RequestMapping(value = "findThreeManList", method = RequestMethod.GET)
	public AjaxResponse findThreeManList(@RequestParam("userID") Integer userID,
			@RequestParam("tableType") Integer tableType) {
		logger.info("\n======== 查询  科室/大队  模块主列表  ========\n");
		boolean flag = false;
		List<ThreeMainList> findThreeMainList = null;
		try {
			findThreeMainList = threeTableService.findThreeMainList(userID, tableType);
			flag = true;
		} catch (Exception e) {
			flag = false;
			e.printStackTrace();
		}
		logger.info("\n======== 结果 : " + (flag == true ? "成功" : "失败") + " ========\n");
		logger.info("\n======== 结果值 : \n" + JSON.toJSONString(findThreeMainList) + " ========\n");
		if (flag) {
			return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, findThreeMainList);
		} else {
			return AjaxResponse.reponseBody(Constant.FAIL_CODE, Constant.FAIL_MSG, "异常");
		}
	}

	@ApiOperation(value = "1-11:查询检查人待分配任务", notes = "userID : 用户id")
	@RequestMapping(value = "findTaskAllotByUid", method = RequestMethod.GET)
	@ResponseBody
	public AjaxResponse findTaskAllotByUid(@RequestParam("userID") Integer id) {
		logger.info("\n======== 查询检查人待分配任务  ========\n");
		boolean flag = false;
		List<ThreeTaskAllot> findThreeTaskAllot = null;
		try {
			findThreeTaskAllot = threeTableService.findThreeTaskAllot(id);
			flag = true;
		} catch (Exception e) {
			flag = false;
			e.printStackTrace();
		}
		logger.info("\n======== 结果 : " + (flag == true ? "成功" : "失败") + " ========\n");
		logger.info("\n======== 结果值 : \n" + JSON.toJSONString(findThreeTaskAllot) + " ========\n");
		if (flag) {
			return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, findThreeTaskAllot);
		} else {
			return AjaxResponse.reponseBody(Constant.FAIL_CODE, Constant.FAIL_MSG, "异常");
		}
	}
	

	@ApiOperation(value = "1-12:修改检查人待分配任务", notes = "userID : 用户id<br>userIDStr : 自查用户字符串")
	@RequestMapping(value = "threeTaskAllotByTaskID", method = RequestMethod.POST)
	@ResponseBody
	public AjaxResponse threeTaskAllotByTaskID(@RequestBody UpdateThreeTaskAllot taskAllot) {
		logger.info("\n======== 查询检查人待分配任务  ========\n");
		boolean flag = false;
		Integer updateThreeTaskAllot = null;
		try {
			updateThreeTaskAllot = threeTableService.updateThreeTaskAllot(taskAllot);

			flag = (updateThreeTaskAllot > 0) ? true : false;
		} catch (Exception e) {
			flag = false;
			e.printStackTrace();
		}
		logger.info("\n======== 结果 : " + (flag == true ? "成功" : "失败") + " ========\n");
		if (flag) {
			return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, (flag == true ? "成功" : "失败"));
		} else {
			return AjaxResponse.reponseBody(Constant.FAIL_CODE, Constant.FAIL_MSG, (flag == true ? "成功" : "失败"));
		}
	}

	@ApiOperation(value = "1-21查询自查人任务--列表", notes = "")
	@RequestMapping(value = "findThreeTaskSelf", method = RequestMethod.POST)
	@ResponseBody
	public AjaxResponse findThreeTaskSelf(@RequestBody FindThreeTaskSelf taskSelf) {
		logger.info("\n======== 查询自查人任务列表  ========\n");
		boolean flag = false;
		List<Map<String, Object>> list = new ArrayList<>();
		Map<String, Object> map = null;
		try {
			List<ThreeTaskSelf> findThreeTaskSelf = threeTableService.findThreeTaskSelf(taskSelf);
			//
			for (ThreeTaskSelf item : findThreeTaskSelf) {
				map = new HashMap<>();
				map.put("taskID", item.getTaskID());
				map.put("threeName", item.getThreeName());
				String selfTime = (item.getSelfTime() == null) ? "" : item.getSelfTime();
				map.put("selfTime", selfTime);
				// map.put("stateName", item.getStateName());
				map.put("state", item.getState());
				list.add(map);
			}

			flag = true;
		} catch (Exception e) {
			flag = false;
			e.printStackTrace();
		}
		logger.info("\n======== 结果 : " + (flag == true ? "成功" : "失败") + " ========\n");
		logger.info("\n======== 结果值 : \n" + JSON.toJSONString(list) + " ========\n");
		if (flag) {
			return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, list);
		} else {
			return AjaxResponse.reponseBody(Constant.FAIL_CODE, Constant.FAIL_MSG, "异常");
		}
	}

	@ApiOperation(value = "1-21-11根据自查任务ID 查询详情表信息", notes = "selfTask:任务详情  <br> items:任务检查项")
	@RequestMapping(value = "findThreeTaskSelfByID", method = RequestMethod.GET)
	@ResponseBody
	public AjaxResponse findThreeTaskSelfByID(@RequestParam("taskID") Integer id) {
		logger.info("\n======== 根据自查任务ID 查询详情表信息  ========\n");
		boolean flag = false;
		Map<String, Object> map = null;
		try {
			map = threeTableService.findThreeTaskSelfByID(id);
			flag = true;
		} catch (Exception e) {
			flag = false;
			e.printStackTrace();
		}
		logger.info("\n======== 结果 : " + (flag == true ? "成功" : "失败") + " ========\n");
		logger.info("\n======== 结果值 : \n" + JSON.toJSONString(map) + " ========\n");
		if (flag) {
			return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, map);
		} else {
			return AjaxResponse.reponseBody(Constant.FAIL_CODE, Constant.FAIL_MSG, "异常");
		}
	}

	@ApiOperation(value = "1-21-12:修改自查任务信息", notes = "传入参数:<br> taskSelf:自查任务详情信息<br>items:自查任务所有检查项<br>")
	@RequestMapping(value = "updateThreeTaskSelf", method = RequestMethod.POST)
	@ResponseBody
	public AjaxResponse updateThreeTaskSelf(HttpServletRequest request) {
		logger.info("\n======== 修改自查任务信息  ========\n");
		// 存放图片的路径
		String imgPath = localConfig.getPicture_upload();
		boolean flag = false;
		Map<String, Object> map = new HashMap<>();
		try {
			// JSON 字符串
			String body = request.getParameter("body");
			logger.info("------------param:" + body);
			// json 转对象
			Map<String, Object> hashMap = JSON.parseObject(body);
			logger.info("\n=====" + hashMap + "=====\n");
			// get自查信息 ==
			String string = hashMap.get("taskSelf").toString();
			
			ThreeTaskSelf parseObject = JSON.parseObject(string,ThreeTaskSelf.class);
			map.put("taskSelf", parseObject);
			// get 检查项
			String itemsStr = "";
			List<ThreeItem> items = null;
			if(hashMap.containsKey("items")){
				itemsStr = hashMap.get("items").toString();
				items = JSON.parseArray(itemsStr,ThreeItem.class);
			}
			
			if (items != null) {
				// 获取数据实体
				Collection<Part> parts = request.getParts();
				// 文件后缀
				String suffix = "";
				// 文件名
				String fileName = "";
				// 图片集合
				List<String> list = new ArrayList<>();
				int i = 0;
				Random random = new Random();
				// 循环解析
				for (Part part : parts) {
					if (!part.getName().toString().equals("taskSelf") && !part.getName().toString().equals("items") && !part.getName().toString().equals("body")) {
						// 获取 范围内随机数
						int nextInt = random.nextInt(999999 - 100000) + 100000;
						i++;
						fileName = part.getName();
						// 前缀 ---- 检查项 ID
						String prefix = fileName.substring(0, fileName.indexOf("-") + 1);
						suffix = fileName.substring(fileName.lastIndexOf("."));
						// 写入文件到 指定文件夹 imgPath
						String file = prefix + String.valueOf(System.currentTimeMillis()) + 
								String.valueOf(nextInt) + i
								+ suffix;
						// 添加到 文件集合
						list.add(file);
						// 写入文件
						part.write(imgPath + file);
					}
				}

				// 2 解析图片==
				List<String> fileStr = null;
				if (items.size() > 0 && list.size() > 0) {
					// 循环分类存入图片
					for (ThreeItem item : items) {
						fileStr = new ArrayList<>();
						for (String str : list) {
							// 前缀 ---- 检查项 ID
							String prefix = str.substring(0, str.indexOf("-"));
							if (Integer.parseInt(prefix) == item.getItemId()) {
								fileStr.add(str);
							}
						}
						if (fileStr.size() > 0) {
							String imgsStr = ListToString.stringListToString(fileStr, ",");
							item.setContent(imgsStr);
						}
					}
				}
				map.put("items", items);
			}
			flag = threeTableService.updateThreeTaskSelf(map);

		} catch (Exception e) {
			flag = false;
			e.printStackTrace();
		}
		logger.info("\n======== 结果 : " + (flag == true ? "成功" : "失败") + " ========\n");
		if (flag) {
			return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, (flag == true ? "成功" : "失败"));
		} else {
			return AjaxResponse.reponseBody(Constant.FAIL_CODE, Constant.FAIL_MSG, (flag == true ? "成功" : "失败"));
		}
	}

	// 类型转换
	List<ThreeItem> extracted(Map<String, Object> map) {
		List<ThreeItem> list = new ArrayList<>();
		Set<String> keySet = map.keySet();
		for (String item : keySet) {
			list.add((ThreeItem) map.get(item));
		}
		return list;
	}

}
